import Vue from 'vue'
import Router from 'vue-router'
import store from '../store'
import { getCookie } from '../config/mUntils'
import { setToken } from '../service/get-data'
import { HIDDENSEARCH, SHOPHIDE, SHOPBACKSHOW } from '../store/mutations-types'
import { FLASH_USER } from '../store/modules/user/mutations-types'
import { eventBus } from '../tool/events-bus'
// import {MessageBox} from 'element-ui'

const Index = r => require.ensure([], () => r(require('@/pages/index/index.vue')), 'index')
const JanuaryActicityExplain = r => require.ensure([], () => r(require('@/pages/activity/January/explain.vue')), 'JanuaryActicityExplain')
const JanuaryYourenField = r => require.ensure([], () => r(require('@/pages/activity/January/yourenField.vue')), 'JanuaryYourenField')
const Newyear = r => require.ensure([], () => r(require('@/pages/activity/January/newyear.vue')), 'Newyear')

const activityYear = r => require.ensure([], () => r(require('@/pages/activity/december/activityYear.vue')), 'activityYear')
const SendCoupon = r => require.ensure([], () => r(require('@/pages/activity/november/coupon.vue')), 'SendCoupon')

const BrandCenter = r => require.ensure([], () => r(require('@/pages/brandCenter/index.vue')), 'BrandCenter')
const ProductList = r => require.ensure([], () => r(require('@/pages/productList/productlist.vue')), 'ProductList')
const ProductDetail = r => require.ensure([], () => r(require('@/pages/productDetail/productdetail.vue')), 'ProductDetail')

const Activityshopcart = r => require.ensure([], () => r(require('@/pages/shopcart/activityshopcart.vue')), 'Activityshopcart') // 满享测试购物车
const ShopCart = r => require.ensure([], () => r(require('@/pages/shopcart/shopcartActivity.vue')), 'ShopCart')
const OrderInfo = r => require.ensure([], () => r(require('@/pages/shopcart/orderInfoComfirm.vue')), 'OrderInfo')
const PersonalCenter = r => require.ensure([], () => r(require('@/pages/personalCenter/index.vue')), 'PersonalCenter')
const OrderManage = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/orderManage.vue')), 'OrderManage')
const Invoice = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/invoice.vue')), 'Invoice')
const HelpCenter = r => require.ensure([], () => r(require('@/pages/helpCenter/index.vue')), 'HelpCenter')
const HelpContent = r => require.ensure([], () => r(require('@/pages/helpCenter/helpcontent.vue')), 'HelpContent')
const NoticeContent = r => require.ensure([], () => r(require('@/pages/helpCenter/noticecontent.vue')), 'HelpContent')
const Problem = r => require.ensure([], () => r(require('@/pages/helpCenter/problem.vue')), 'Problem')
const Notice = r => require.ensure([], () => r(require('@/pages/helpCenter/notice.vue')), 'Notice')
const OrderDetail = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/orderDetail.vue')), 'OrderDetail')
const CustomerService = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/customerService/applySale.vue')), 'CustomerService')
const ServiceSuccess = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/customerService/serviceSuccess.vue')), 'ServiceSuccess')
const TransactionFlow = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/transactionFlow.vue')), 'TransactionFlow')
const RebateMember = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/rebateMember.vue')), 'RebateMember')
const GiftsCenter = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/giftsCenter.vue')), 'GiftsCenter')
const PersonalInfo = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/personalInfo.vue')), 'PersonalInfo')
const MemberCenter = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/memberCenter.vue')), 'MemberCenter')
const memberPrivilege = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/memberPrivilege.vue')), 'memberPrivilege')
const MemberProcurement = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/memberProcurement.vue')), 'MemberProcurement')
const MemberAcceptance = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/memberAcceptance.vue')), 'MemberAcceptance')
const MemberBalance = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/memberBalance.vue')), 'MemberBalance')
const DiscountVoucher = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/discountVoucher.vue')), 'DiscountVoucher')
const BrandVoucher = r => require.ensure([], () => r(require('@/pages/personalCenter/purchaseCenter/brandVoucher.vue')), 'BrandVoucher')
const SafeCenter = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/safeCenter.vue')), 'SafeCenter')
const RecevieAddr = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/receiveAddr.vue')), 'RecevieAddr')
const InvoiceList = r => require.ensure([], () => r(require('@/pages/personalCenter/personalData/invoiceInfo.vue')), 'InvoiceList')
const Feedback = r => require.ensure([], () => r(require('@/pages/personalCenter/saleAfter/feedback.vue')), 'Feedback')
const SystemMsg = r => require.ensure([], () => r(require('@/pages/personalCenter/systemMes/message.vue')), 'SystemMsg')
const DetailMsg = r => require.ensure([], () => r(require('@/pages/personalCenter/systemMes/detailmsg.vue')), 'DetailMsg')
const InquiryMsg = r => require.ensure([], () => r(require('@/pages/personalCenter/systemMes/inquiryMes.vue')), 'InquiryMsg')
const Login = r => require.ensure([], () => r(require('@/pages/login/index.vue')), 'Login')
const Register = r => require.ensure([], () => r(require('@/pages/register/index.vue')), 'Register')
const Forget = r => require.ensure([], () => r(require('@/pages/forget/index.vue')), 'Forget')
const CompanyCert = r => require.ensure([], () => r(require('@/pages/companyCert/index.vue')), 'CompanyCert')
const ComCertUploadSucceed = r => require.ensure([], () => r(require('@/pages/companyCert/comCertUploadSucceed.vue')), 'ComCertUploadSucceed')
// const ComCertUploadFailure = r => require.ensure([], () => r(require('@/pages/companyCert/comCertUploadFailure.vue')), 'ComCertUploadFailure')
const QrcodePay = r => require.ensure([], () => r(require('@/pages/orderpay/qrcodePay.vue')), 'QrcodePay')
const Paystatus = r => require.ensure([], () => r(require('@/pages/orderpay/paystatus.vue')), 'Paystatus')
const Cashier = r => require.ensure([], () => r(require('@/pages/orderpay/cashier.vue')), 'Cashier')
const OrderSubmitRemind = r => require.ensure([], () => r(require('@/pages/orderpay/orderSubmitRemind.vue')), 'OrderSubmitRemind')
const SearchPage = r => require.ensure([], () => r(require('@/pages/searchPage/index.vue')), 'SearchPage')
const ModelList = r => require.ensure([], () => r(require('@/pages/searchPage/modelList.vue')), 'ModelList')

// 商品分类列表
const Hot = r => require.ensure([], () => r(require('@/pages/classify/hot.vue')), 'Hot')
const NewUsers = r => require.ensure([], () => r(require('@/pages/activity/getNewUsers.vue')), 'NewUsers')
const YouRen = r => require.ensure([], () => r(require('@/pages/specialPro/youren.vue')), 'YouRen')
// 活动
const ActivityArea = r => require.ensure([], () => r(require('@/pages/activity/october/activityArea.vue')), 'ActivityArea')
const ActivityGoods = r => require.ensure([], () => r(require('@/pages/activity/activityTemplate/hotGoods.vue')), 'ActivityGoods')
const ActivityBrand = r => require.ensure([], () => r(require('@/pages/activity/activityTemplate/discountBrand.vue')), 'ActivityBrand')

const ActivityRank = r => require.ensure([], () => r(require('@/pages/activity/september19/activityRank.vue')), 'ActivityRank')
const ActivityNewYear = r => require.ensure([], () => r(require('@/pages/activity/January20/ActivityNewYear.vue')), 'ActivityNewYear')
const ActivityRank618 = r => require.ensure([], () => r(require('@/pages/activity/June20/ActivityRank618.vue')), 'ActivityRank618')
const ActivityRank12 = r => require.ensure([], () => r(require('@/pages/activity/november20/ActivityRank.vue')), 'ActivityRank12')
const ActivityRank2107 = r => require.ensure([], () => r(require('@/pages/activity/july21/ActivityRank.vue')), 'ActivityRank2107')

const ActivityFull = r => require.ensure([], () => r(require('@/pages/activity/fullEnjoyActivity/mainActivity.vue')), 'ActivityFull')
const ScreenActivity = r => require.ensure([], () => r(require('@/pages/activity/fullEnjoyActivity/screenActivity.vue')), 'ScreenActivity')

// 测试
const Test = r => require.ensure([], () => r(require('@/pages/test/test.vue')), 'Test')

// 404页面
const ErrorPage = r => require.ensure([], () => r(require('@/pages/error/404.vue')), 'ErrorPage')
Vue.use(Router)

// url 使用小写
const myRouter = new Router({
  // mode: 'history',
  // base: '/knife/',
  linkActiveClass: 'router-active',
  routes: [
    {
      path: '/test',
      name: 'Test',
      component: Test
    },
    {
      path: '/',
      redirect: '/index'
    },
    {
      path: '/index',
      name: 'Index',
      component: Index
    },
    {
      path: '/login',
      name: 'Login',
      component: Login,
      meta: {
        hiddenSearch: true,
        isLoginPage: true
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: Register,
      meta: {
        hiddenSearch: true
      }
    },
    {
      path: '/forget',
      name: 'Forget',
      component: Forget,
      meta: {
        hiddenSearch: true
      }
    },
    {
      path: '/newusers',
      name: 'NewUsers',
      component: NewUsers,
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/youren',
      name: 'YouRen',
      component: YouRen
    },
    {
      path: '/companycert',
      component: CompanyCert,
      name: 'CompanyCert',
      meta: {
        hiddenSearch: true
      },
      beforeEnter: (to, from, next) => {
        if (!getCookie('Token')) {
          next({
            path: '/login',
            query: { redirect: to.fullPath }
          })
        } else {
          setToken()
          next()
        }
      }
    },
    // {
    //   path: '/uploadcert',
    //   component: CompanyCert,
    //   name: 'UploadCert',
    //   meta: {
    //     hiddenSearch: true
    //   },
    //   beforeEnter: (to, from, next) => {
    //     if (!getCookie('Token')) {
    //       next({
    //         path: '/login',
    //         query: { redirect: to.fullPath }
    //       })
    //     } else {
    //       setToken()
    //       next()
    //     }
    //   }
    // },
    {
      path: '/comcertuploadresult/:type',
      component: ComCertUploadSucceed,
      name: 'ComCertUploadResult'
    },
    {
      path: '/productlist',
      component: ProductList,
      name: 'ProductList'
    },
    {
      path: '/sendcoupon',
      component: SendCoupon,
      name: 'SendCoupon'
    },
    {
      path: '/sendreaward',
      component: activityYear,
      name: 'activityYear'
    },
    {
      path: '/activityarea',
      component: ActivityArea,
      name: 'ActivityArea'
    },
    {
      path: '/activityrank',
      component: ActivityRank,
      name: 'ActivityRank'
    },
    {
      path: '/activitynewyear',
      component: ActivityNewYear,
      name: 'ActivityNewYear'
    },
    {
      path: '/ActivityRank618',
      component: ActivityRank618,
      name: 'ActivityRank618'
    },
    {
      path: '/ActivityRank12',
      component: ActivityRank12,
      name: 'ActivityRank12'
    },
    {
      path: '/ActivityRank2107',
      component: ActivityRank2107,
      name: 'ActivityRank2107'
    },
    {
      path: '/HOT_SALE',
      component: ActivityGoods,
      name: 'ActivityGoods'
    },
    {
      path: '/BRAND_AREA',
      component: ActivityBrand,
      name: 'ActivityBrand'
    },
    {
      path: '/FULL_DISCOUNT',
      component: ActivityFull,
      name: 'ActivityFull'
    },
    {
      path: '/screenactivity/:activityId',
      component: ScreenActivity,
      name: 'ScreenActivity'
    },
    {
      path: '/januaryexplain',
      component: JanuaryActicityExplain,
      name: 'JanuaryActicityExplain'
    },
    {
      path: '/januaryyourenfield',
      component: JanuaryYourenField,
      name: 'JanuaryYourenField'
    },
    {
      path: '/newyear',
      component: Newyear,
      name: 'Newyear'
    },
    {
      path: '/searchpage',
      component: SearchPage,
      name: 'SearchPage'
    },
    {
      path: '/modellist',
      component: ModelList,
      name: 'ModelList'
    },
    {
      path: '/hot',
      component: Hot,
      name: 'Hot'
    },
    {
      path: '/new',
      component: Hot,
      name: 'New'
    },
    {
      path: '/brandcenter',
      component: BrandCenter,
      name: 'BrandCenter'
    },
    {
      path: '/qrcodePay',
      component: QrcodePay,
      name: 'QrcodePay',
      meta: {
        requireAuth: true,
        hiddenSearch: true
      }
    },
    {
      path: '/paystatus',
      component: Paystatus,
      name: 'Paystatus',
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/cashier',
      component: Cashier,
      name: 'Cashier',
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/ordersubmitremind/:orderId',
      component: OrderSubmitRemind,
      name: 'OrderSubmitRemind',
      meta: {
        requireAuth: true
      }
    },
    {
      path: '/productlist/detail/:commodityID',
      component: ProductDetail,
      name: 'productDetail'
    },
    {
      path: '/activityshopcart',
      component: Activityshopcart,
      name: 'ActivityShopCart',
      meta: {
        shopcartHide: true, // 是否隐藏购物车组件
        shopcartBackShow: true, // 是否显示购物车返回
        requireAuth: true // 进入该路由是需要登录的
      }
    },
    {
      path: '/shopcart',
      component: ShopCart,
      name: 'ShopCart',
      meta: {
        shopcartHide: true, // 是否隐藏购物车组件
        shopcartBackShow: true, // 是否显示购物车返回
        requireAuth: true // 进入该路由是需要登录的
      }
    },
    {
      path: '/shopcart/ordercomfirm',
      component: OrderInfo,
      name: 'OrderInfo',
      meta: {
        shopcartHide: true,
        requireAuth: true // 进入该路由是需要登录的
      }
    },
    {
      path: '/purchase',
      component: PersonalCenter,
      name: 'PersonalCenter',
      meta: {
        requireAuth: true,
        nocompanyAuth: true
      },
      children: [
        {
          path: '/ordermanage',
          component: OrderManage,
          name: 'orderManage',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/ordermanage/orderdetail/:orderId',
          component: OrderDetail,
          name: 'orderDetail',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/ordermanage/customerservice',
          component: CustomerService,
          name: 'customerService',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/invoice',
          component: Invoice,
          name: 'invoice',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: 'transactionflow',
          component: TransactionFlow,
          name: 'transactionFlow',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/rebatemember',
          component: RebateMember,
          name: 'rebateMember',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/giftscenter',
          component: GiftsCenter,
          name: 'giftsCenter',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/membercenter/personalinfo',
          component: PersonalInfo,
          name: 'personalInfo',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/membercenter',
          component: MemberCenter,
          name: 'memberCenter',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/membercenter/procurement',
          component: MemberProcurement,
          name: 'MemberProcurement',
          meta: {
            requireAuth: true,
            nocompanyAuth: false
          }
        },
        {
          path: '/membercenter/acceptance',
          component: MemberAcceptance,
          name: 'MemberAcceptance',
          meta: {
            requireAuth: true,
            nocompanyAuth: false
          }
        },
        {
          path: '/membercenter/balance',
          component: MemberBalance,
          name: 'MemberBalance',
          meta: {
            requireAuth: true,
            nocompanyAuth: false
          }
        },
        {
          path: '/membercenter/privilege',
          component: memberPrivilege,
          name: 'memberPrivilege',
          meta: {
            requireAuth: true,
            nocompanyAuth: false
          }
        },
        {
          path: '/info/discountvoucher',
          component: DiscountVoucher,
          name: 'discountVoucher',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/giftscenter/brandVoucher',
          component: BrandVoucher,
          name: 'brandVoucher',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/info/safecenter',
          component: SafeCenter,
          name: 'safeCenter',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/info/recevieaddr',
          component: RecevieAddr,
          name: 'recevieAddr',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: '/info/invoicelist',
          component: InvoiceList,
          name: 'invoiceList',
          meta: {
            nocompanyAuth: false
          }
        },
        {
          path: 'saleAfter/feedback',
          component: Feedback,
          name: 'feedback'
        },
        {
          path: 'message/systemmsg',
          component: SystemMsg,
          name: 'systemMsg'
        },
        {
          path: 'message/systemmsg/detailmsg',
          component: DetailMsg,
          name: 'detailMsg'
        },
        {
          path: 'message/inquiryMsg',
          component: InquiryMsg,
          name: 'inquiryMsg',
          meta: {
            nocompanyAuth: false
          }
        }
      ]
    },
    {
      path: '/servicesuccess', // type refund regoods
      component: ServiceSuccess,
      name: 'serviceSuccess'
    },
    {
      path: '/help',
      component: HelpCenter,
      name: 'HelpCenter',
      children: [
        {
          path: '/problem',
          component: Problem,
          name: 'Problem'
        },
        {
          path: '/problem/helpcontent/:id',
          component: HelpContent,
          name: 'HelpContent'
        },
        {
          path: '/notice/:type',
          component: Notice,
          name: 'Notice'
        },
        {
          path: '/notice/:type/noticecontent/:id',
          component: NoticeContent,
          name: 'NoticeContent'
        }
      ]
    },
    {
      path: '*',
      component: ErrorPage
    }
  ],
  scrollBehavior (to, from, savedPosition) {
    if (to.hash) {
      return { selector: to.hash }
      // return {x: 0, y: 1200}
    } else {
      return { x: 0, y: 0 }
    }
  }
})

myRouter.beforeEach((to, from, next) => {
  // 设置请求头
  setToken()
  // 包括刷新状态 获取isLogin的值
  store.commit(FLASH_USER)
  if (to.matched.some(record => record.meta.hiddenSearch)) {
    store.commit(HIDDENSEARCH, true)
  } else {
    store.commit(HIDDENSEARCH, false)
    if (to.matched.some(record => record.meta.shopcartHide)) {
      store.commit(SHOPHIDE, true)
    } else {
      store.commit(SHOPHIDE, false)
    }
  }
  // 购物车返回
  if (to.matched.some(record => record.meta.shopcartBackShow)) {
    store.commit(SHOPBACKSHOW, true)
  } else {
    store.commit(SHOPBACKSHOW, false)
  }
  // 切换路由 login页不去请求，存在Token值 就去更新用户信息
  if (to.matched.some(record => record.meta.isLoginPage)) {
    next()
  } else if (getCookie('Token')) {
    store.dispatch('getUserData')
  }
  if (to.matched.some(record => record.meta.requireAuth)) {
    // if not, redirect to login page.
    if (!getCookie('Token')) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      // 不需要认证直接登录进去
      // 如果跳转路由本身含有nocompanyAuth字段且为false，将会拦截，可以用于在父级路由不需要验证的情况下将子路由设置为需要验证(子路由meta添加nocompanyAuth: false)
      if (to.matched.some(record => record.meta.nocompanyAuth) && (to.meta.hasOwnProperty('nocompanyAuth') ? to.meta.nocompanyAuth : true)) {
        next()
        return
      }
      // 1. 获取用户信息 => 失效 1 token清空 2. 去登录
      // 0:审核中,1:审核通过, 2:审核失败, 3: 未审核
      store.dispatch('getUserData').then(() => {
        // debugger
        let isExam = store.state.user.isExam
        if (isExam === 1) {
          next()
        } else if (isExam === 2) {
          // 失败2
          store.commit('EXAMFAIL', true)
          // eventBus.$emit('show:alert', '您还需完成企业认证')
          // next('/companycert')
        } else if (isExam === 3) {
          store.commit('EXAMNODO', true)
        } else if (isExam === 0) {
          eventBus.$emit('show:alert', '您的企业信息还在审核中,请稍等...')
          next('/index')
        }
      })
    }
  } else {
    next() // 确保一定要调用 next()
  }
})

export default myRouter
